package com.duduli.li;

import com.duduli.li.mapper.JdMapper;
import com.duduli.li.po.ProductPrice;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.io.Reader;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetWebProductPrice {
    public String getJsonString(String url) throws IOException {
        Document doc = Jsoup.connect(url).ignoreContentType(true).get();
        System.out.println(doc.body().text());
        return doc.body().text().substring(1,doc.body().text().length()-1);
    }

    public List<ProductPrice> getPrice() throws IOException {
        List<ProductPrice> p = new ArrayList<ProductPrice>();
        int i = 1;
        Reader reader = Resources.getResourceAsReader("config/conf.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = factory.openSession();
        JdMapper jm = sqlSession.getMapper(JdMapper.class);
        String str = String.valueOf(Math.abs(new Random().nextInt()*100000000));
            for(String s : jm.getProductId()){
                if(i%10000 == 0){
                    str = String.valueOf(Math.abs(new Random().nextInt()*100000000));
                }
                ProductPrice pp = new ProductPrice();
                String url = "https://p.3.cn/prices/mgets?&pduid="+str+"&skuIds=J_"+s;
                System.out.println(url);
//            JdWinePo jdWinePo = om.readValue(getWineFromJdJson(url),JdWinePo.class);
                String pattern = "\"p\":\"\\d*.\\d*\"";
                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(getJsonString(url));
                if (m.find( )) {
                    System.out.println(m.group(0).substring(5,m.group(0).length()-1));
                    pp.setPrice(m.group(0).substring(5,m.group(0).length()-1));
                } else {
                    System.out.println("NO MATCH");
                }
                pp.setId(s);
                pp.setTime(String.valueOf(LocalDate.now()));
                p.add(pp);
                i++;
                jm.insertProductPrice(pp);
                sqlSession.commit();
            }
        sqlSession.close();
//        jm.getProductId();

        return p;
    }

    public static void main(String[] args) throws IOException {
        GetWebProductPrice g = new GetWebProductPrice();
        g.getPrice();
    }
}
